package com.example.adapter;


import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.database.DatabaseHelper;
import com.example.pojo.Teacher;
import com.example.student.R;

import java.util.List;

public class TeacherAdapter extends RecyclerView.Adapter<TeacherAdapter.TeacherViewHolder> {
    private List<Teacher> teacherList;
    private DatabaseHelper databaseHelper;

    // 构造函数
    public TeacherAdapter(List<Teacher> teacherList, DatabaseHelper databaseHelper) {
        this.teacherList = teacherList;
        this.databaseHelper = databaseHelper;
    }

    // 创建 ViewHolder
    @NonNull
    @Override
    public TeacherViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_teacher, parent, false);
        return new TeacherViewHolder(view);
    }

    // 绑定数据
    @Override
    public void onBindViewHolder(@NonNull TeacherViewHolder holder, int position) {
        Teacher teacher = teacherList.get(position);
        holder.bind(teacher);

        // 设置删除按钮点击事件
        holder.btnDelete.setOnClickListener(v -> {
            // 从数据库中删除教师
            databaseHelper.deleteTeacher(String.valueOf(teacher.getTeacherId()));

            // 从列表中移除教师
            teacherList.remove(position);
            notifyItemRemoved(position);
            notifyItemRangeChanged(position, teacherList.size());

            // 提示删除成功
            Toast.makeText(holder.itemView.getContext(), "删除成功", Toast.LENGTH_SHORT).show();
        });
    }

    // 返回数据项数量
    @Override
    public int getItemCount() {
        return teacherList.size();
    }

    // ViewHolder 类
    public static class TeacherViewHolder extends RecyclerView.ViewHolder {
        private TextView textTeacherId, textName, textCollegeJob, textOfficePhone;
        private ImageButton btnDelete;

        public TeacherViewHolder(@NonNull View itemView) {
            super(itemView);
            textTeacherId = itemView.findViewById(R.id.textTeacherId);
            textName = itemView.findViewById(R.id.textName);
            textCollegeJob = itemView.findViewById(R.id.textCollegeJob);
            textOfficePhone = itemView.findViewById(R.id.textOfficePhone);
            btnDelete = itemView.findViewById(R.id.btnDelete);
        }

        // 绑定教师数据
        public void bind(Teacher teacher) {
            textTeacherId.setText("教师ID：" + teacher.getTeacherId());
            textName.setText("姓名：" + teacher.getTeacherName());
            textCollegeJob.setText("学院：" + teacher.getCollege() + " 职位：" + teacher.getJob());
            textOfficePhone.setText("办公室：" + teacher.getOffice() + " 电话：" + teacher.getPhone());
        }
    }
}